import axios, { AxiosPromise } from 'axios'
import FormData from 'form-data'

export interface KandinskyRunResponse {
  status: 'INITIAL' | 'PROCESSING'
  uuid: string
}

export interface KandinskyResponse {
  uuid: string
  status: 'DONE'
  images: string[]
  censored: boolean
}

export interface GenerateParameters {
  query: string
}

export interface KandinskyRequest {
  type: 'GENERATE'
  generateParams: GenerateParameters
}

function makeParameters(query: string): KandinskyRequest {
  return {
    type: 'GENERATE',
    generateParams: {
      query,
    },
  }
}

export async function requestAvatar(query: string): AxiosPromise<KandinskyRunResponse> {
  const data = new FormData()
  data.append('params', JSON.stringify(makeParameters(query)), {
    contentType: 'application/json',
  })
  data.append('model_id', '4')
  const config = {
    method: 'post',
    maxBodyLength: Number.POSITIVE_INFINITY,
    url: 'https://api-key.fusionbrain.ai/key/api/v1/text2image/run',
    headers: {
      'X-Key': 'Key 00EFACEA2F8D15CA717D9DDD785FC8CE',
      'X-Secret': 'Secret DA1AB3A635753EF1EDA33EDDFA8AD422',
      ...data.getHeaders(),
    },
    data: data,
  }

  return axios.request(config)
}

export async function checkStatusImg(uuid: string): AxiosPromise<KandinskyResponse | KandinskyRunResponse> {
  const config = {
    method: 'get',
    url: `https://api-key.fusionbrain.ai/key/api/v1/text2image/status/${uuid}`,
    headers: {
      'X-Key': 'Key 00EFACEA2F8D15CA717D9DDD785FC8CE',
      'X-Secret': 'Secret DA1AB3A635753EF1EDA33EDDFA8AD422',
    },
  }

  return axios.request(config)
}
